package com.hooper.cmn.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.hooper.cmn.mapper.DictMapper;
import com.hooper.cmn.vo.DictImportVO;
import com.hooper.cmn.vo.DictVO;
import com.hooper.hosp.model.cmn.Dict;
import com.hooper.hospital.common.exception.HospitalException;
import com.hooper.hospital.common.result.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author Tim Hooper
 * @version 1.0
 * @time 2022/09/27/10:24
 */
@Slf4j
public class EasyExcelListener extends AnalysisEventListener<DictImportVO> {

    private DictMapper dictMapper;

    public EasyExcelListener(DictMapper dictMapper){
        this.dictMapper = dictMapper;
    }

    public EasyExcelListener() {
    }

    @Override
    public void invoke(DictImportVO dictImportVO, AnalysisContext analysisContext) {
        log.info("the listener is working ");
        if (dictImportVO == null) {
            throw new HospitalException(ResultCodeEnum.DATA_ERROR);
        }
        Dict dict = new Dict();
        dict.setDictCode(dictImportVO.getDictCode());
        dict.setId(dictImportVO.getId());
        dict.setParentId(dictImportVO.getParentId());
        dict.setName(dictImportVO.getName());
        dict.setValue(dictImportVO.getValue());
        dict.setDictCode(dictImportVO.getDictCode());
        boolean saved = dictMapper.insert(dict) > 0;
        if (!saved) {
            throw new HospitalException(ResultCodeEnum.DATA_ERROR);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info(" successfully imported");
    }
}
